package com.igeek.health.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.igeek.health.entity.Member;
import com.igeek.health.mapper.MemberMapper;
import com.igeek.health.service.IMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.health.utils.JwtHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fengqq
 * @since 2024-08-26
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    //会员快捷登录
    @Transactional
    @Override
    public String login(String telephone) {
        //1.根据手机号 查询 会员信息
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<Member>().eq(Member::getPhoneNumber, telephone);
        List<Member> memberList = baseMapper.selectList(queryWrapper);

        Member member = null;
        if(CollectionUtil.isEmpty(memberList)){
            //2.1 如果不存在会员信息 则直接注册会员
            member = new Member();
            member.setFileNumber(UUID.randomUUID().toString().replaceAll("-",""));
            member.setName(telephone);
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            baseMapper.insert(member);
        }else {
            //2.2 如果已存在会员信息 则直接登录成功
            member = memberList.get(0);
        }

        //3.封装token数据
        String token = JwtHelper.createToken(member.getId(), member.getName());
        return token;
    }
}
